(function () {
    var table = function (BSId, url, columns) {
        this.btInstance = null;
        this.BSId = BSId;
        this.url = url;
        this.method = "post";
        this.paginationType = "client";
        this.toolbarId = "#" + BSId + "-toolbar";
        this.columns = columns;
        this.data = {};
        this.queryParams = {};
        this.pagination = true;
        this.pageSize = 15;
        this.detailView = false;
        this.detailFormatter = undefined;
        this.treeShowField = undefined;
        this.onLoadSuccess = undefined;
        this.search = true;
    };

    table.prototype = {
        /**
         * 初始化bootstrap table
         */
        init: function () {
            var tableId = this.BSId;
            var that = this;
            this.btInstance =
                $('#' + tableId).bootstrapTable({
                    contentType: "application/x-www-form-urlencoded",
                    url: this.url,				//请求地址
                    method: this.method,		//ajax方式,post还是get
                    ajaxOptions: {				//ajax请求的附带参数
                        data: this.data
                    },
                    toolbar: this.toolbarId,//顶部工具条
                    striped: false,     			//是否显示行间隔色
                    cache: true,      			//是否使用缓存,默认为true
                    pagination: this.pagination,   //是否显示分页（*）
                    sortable: true,      		//是否启用排序
                    sortOrder: "desc",     		//排序方式
                    pageNumber: 1,      			//初始化加载第一页，默认第一页
                    pageSize: this.pageSize,     //每页的记录行数（*）
                    pageList: [15, 50, 100],  	//可供选择的每页的行数（*）
                    queryParamsType: 'limit', 	//默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
                    queryParams: function (param) {
                        return $.extend(that.queryParams, param);
                    }, // 向后台传递的自定义参数
                    sidePagination: this.paginationType,   //分页方式：client客户端分页，server服务端分页（*）
                    strictSearch: false,			//设置为 true启用 全匹配搜索，否则为模糊搜索
                    showColumns: false,     		//是否显示所有的列
                    showRefresh: false,     		//是否显示刷新按钮
                    minimumCountColumns: 2,    	//最少允许的列数
                    clickToSelect: true,    	//是否启用点击选中行
                    search: this.search,
                    searchOnEnterKey: false,		//设置为 true时，按回车触发搜索方法，否则自动触发搜索方法
                    columns: this.columns,		//列数组
                    classes: 'table table-no-bordered',
                    iconSize: 'sm',
                    uniqueId: "id",
                    detailView: this.detailView,
                    detailFormatter: this.detailFormatter,
                    treeShowField: this.treeShowField,
                    onLoadSuccess: this.onLoadSuccess
                });
            return this;
        },
        /**
         * 向后台传递的自定义参数
         * @param param
         */
        setQueryParams: function (param) {
            this.queryParams = param;
            return this;
        },
        /**
         * 设置分页方式：server 或者 client
         */
        setPaginationType: function (type) {
            this.paginationType = type;
            return this;
        },

        setSearch: function(search){
            this.search = search;
            return this;
        },

        setMethod: function (method) {
            this.method = method;
            return this;
        },

        setPageSize: function (pageSize) {
            this.pageSize = pageSize;
            return this;
        },

        setPagination: function(pagination){
            this.pagination = pagination;
            return this;
        },

        setDetailView: function (detailView) {
            this.detailView = detailView;
            return this;
        },

        setDetailFormatter: function (detailFormatter) {
            this.detailFormatter = detailFormatter;
            return this;
        },

        showToolbar: function(bool){
            if(!bool){
                this.toolbarId = undefined;
            }
            return this;
        },


        /**
         * 设置ajax post请求时候附带的参数
         */
        set: function (key, value) {
            if (typeof key == "object") {
                for (var i in key) {
                    if (typeof i == "function")
                        continue;
                    this.data[i] = key[i];
                }
            } else {
                this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
            }
            return this;
        },

        /**
         * 设置ajax post请求时候附带的参数
         */
        setData: function (data) {
            this.data = data;
            return this;
        },

        /**
         * 清空ajax post请求参数
         */
        clear: function () {
            this.data = {};
            return this;
        },

        check: function (callback) {
            var selected = this.btInstance.bootstrapTable('getSelections');
            if(selected.length == 0) {
                layer.alert("请先选中表格中的某一记录！");
                return false;
            } else {
                callback(selected[0]);
                return true;
            }
        },

        getItem: function () {
            var selected = this.btInstance.bootstrapTable('getSelections');
            if(selected.length > 0) {
                return selected[0];
            }
            return null;
        },

        getData: function () {
            return this.btInstance.bootstrapTable('getData');
        },

        getItemById: function (id) {
            var selected = this.btInstance.bootstrapTable('getRowByUniqueId', id);
            if(selected == undefined) {
                return selected;
            }
            return null;
        },

        setTreeShowField: function(treeShowField, initialState){
            if(initialState == undefined){
                initialState = 'expanded';
            }
            var that = this;
            that.treeShowField = treeShowField;
            if(treeShowField != undefined){
                that.onLoadSuccess = function(data) {
                    $('#' + that.BSId).treegrid({
                        initialState: initialState,   //expanded   collapsed
                        treeColumn: 1,
                        expanderExpandedClass: 'fa fa-angle-down',
                        expanderCollapsedClass: 'fa fa-angle-right'
                    });
                }
            }
            return this;
        },

        setOnLoadSuccess: function(onLoadSuccess){
            this.onLoadSuccess = onLoadSuccess;
            return this;
        },

        refresh: function (parms) {
            if (parms) {
                this.btInstance.bootstrapTable('refresh', parms);
            } else {
                this.btInstance.bootstrapTable('refresh');
            }
        },

        refresh2: function (parms) {
            this.btInstance.bootstrapTable('refresh', parms);
        }
    };

    window.Table = table;

}());